package cn.hh.wechatkit.util;

import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.IOException;
import java.io.StringWriter;

/**
 * Created this one by HMH on 2017/7/31.
 */
@Slf4j
public class XmlUtil {
    /**
     * 格式化XML文档
     *
     * @param document xml文档
     * @param charset    字符串的编码
     * @param isTrans    是否对属性和元素值进行转移
     * @return 格式化后XML字符串
     */
    public static String formatXml(Document document, String charset, boolean isTrans) {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(charset);
        StringWriter sw = new StringWriter();
        XMLWriter xw = new XMLWriter(sw, format);
        xw.setEscapeText(isTrans);
        try {
            xw.write(document);
            xw.flush();
            xw.close();
        } catch (IOException e) {
            log.error("格式化XML文档发生异常，请检查！",e);
        }
        return sw.toString();
    }

}
